package com.example.dps;

import java.text.DecimalFormat;
import java.text.NumberFormat;

import org.achartengine.GraphicalView;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.SeekBar.OnSeekBarChangeListener;



public class MortgageCalcActivity extends Activity{
	
	DBHelper dbhelper;
	
	CalcDBHelper calcDBHelper;
	
	DecimalFormat formatter = new DecimalFormat("$#,###");
	
	/** Integer values representing each seekBar. to be used to display values as text in different locations **/
	int homePrice;
	double interestRate;
	int downPayment;
	
	int monthlyExpenses;
	int monthlyIncome;
	
	int principal;
	
	boolean downPaymentCalcSelected = false;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.mortgage_calc_activity);
		
		LayoutInflater layoutInflater = (LayoutInflater) 
		        this.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
		
		
		
		dbhelper = new DBHelper(this);
		
		calcDBHelper = new CalcDBHelper(this);
		
		LinearLayout mortCalcMainContentLayout = (LinearLayout) findViewById(R.id.mortCalcContentLayout);
		
		if(downPaymentCalcSelected == true){
			mortCalcMainContentLayout.addView(layoutInflater.inflate(R.layout.downpayment_calc_layout, mortCalcMainContentLayout, false));
			addPieChart();
			restoreDownPaymentCalcDBValues();
			
		}
		else{
			mortCalcMainContentLayout.addView(layoutInflater.inflate(R.layout.affordability_calc_layout, mortCalcMainContentLayout, false));
			restoreAffordabilityCalcDBValues();
			calculateAffordableHome();
		}

		/** add button and slider listeners **/
		addListeners();
		
		
		
		
		
	}
	

	public void onResume(){
		
		ScrollView sv = (ScrollView) this.findViewById(R.id.scrollView);
		if(sv!=null) sv.scrollTo(0,0);
		
		super.onResume();
		if(downPaymentCalcSelected){
			restoreDownPaymentCalcDBValues();
			
			updateCalculations();
		}
		else{
			restoreAffordabilityCalcDBValues();
			
			updateAffordabilityCalculations();
			
			calculateAffordableHome();
		}
	}

	public void addAffordabilityListeners(){
		
		
		SeekBar monthlyIncomeSB = (SeekBar) findViewById(R.id.monthlyIncomeSlider);
		SeekBar monthlyExpensesSB = (SeekBar) findViewById(R.id.monthlyExpensesSlider);
		SeekBar interestRateSB = (SeekBar) findViewById(R.id.interestRateAffordabilitySlider);
		
		
		/********************************************************************************/
		/** START Monthly Income Seek Bar Listener
		/*******************************************************************************/
		monthlyIncomeSB.setOnSeekBarChangeListener(new OnSeekBarChangeListener(){

			@Override
			public void onProgressChanged(SeekBar seekBar, int progress,
					boolean fromUser) {
				
				int incomeIncrement = 500;
				
				monthlyIncome = progress/incomeIncrement;
				monthlyIncome = monthlyIncome*incomeIncrement;
				
				TextView monthlyIncomeText = (TextView) findViewById(R.id.monthlyIncomeText);
				
				monthlyIncomeText.setText(formatter.format(monthlyIncome));
				
				
				MortgageCalcActivity.this.calculateAffordableHome();
				
				
			}

			@Override
			public void onStartTrackingTouch(SeekBar seekBar) {
				
			}

			@Override
			public void onStopTrackingTouch(SeekBar seekBar) {
				calcDBHelper.updateIncome(monthlyIncome);
			}
			
		});
		
		/** END Monthly Income Seek Bar Listener
		/*******************************************************************************/
		
		
		
		/********************************************************************************/
		/** START Monthly Expenses Seek Bar Listener
		/*******************************************************************************/
		
		monthlyExpensesSB.setOnSeekBarChangeListener(new OnSeekBarChangeListener(){

			@Override
			public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
				
				int expenseIncrement = 500;
				
				monthlyExpenses = progress/expenseIncrement;
				monthlyExpenses = monthlyExpenses*expenseIncrement;
				
				TextView monthlyExpensesText = (TextView) findViewById(R.id.monthlyExpensesText);
				
				monthlyExpensesText.setText(formatter.format(monthlyExpenses));
				
				MortgageCalcActivity.this.calculateAffordableHome();
				
			}

			@Override
			public void onStartTrackingTouch(SeekBar arg0) {
				
			}

			@Override
			public void onStopTrackingTouch(SeekBar arg0) {
				
				calcDBHelper.updateExpenses(monthlyExpenses);
				//MortgageCalcActivity.this.calculateAffordableHome();
			}
			
		});
		
		/** END Monthly Expenses Seek Bar Listener
		/*******************************************************************************/
		
		/********************************************************************************/
		/** START Interest Rate Seek Bar Listener
		/*******************************************************************************/
		interestRateSB.setOnSeekBarChangeListener(new OnSeekBarChangeListener(){
			@Override
			public void onProgressChanged(SeekBar sb, int progress, boolean fromUser) {
				
				
				/**
				 * formats the interest rate to be between 0-10% with %.25 intervals
				 */
				int tempRate = progress;
				tempRate = tempRate/250;
				tempRate = tempRate*250;
				
				interestRate = (double)tempRate;
				interestRate = interestRate/1000;
				
				/** update the associated text values **/
				TextView interestRateSliderValue = (TextView) findViewById(R.id.interestRateAffordabilityText);

				/** Convert to Decimal format with 2 decimal Places **/
				DecimalFormat df = new DecimalFormat("0.00");
				
				interestRateSliderValue.setText(df.format(interestRate).toString()+"%");
				
				MortgageCalcActivity.this.calculateAffordableHome();
		
			}

			@Override
			public void onStartTrackingTouch(SeekBar arg0) {
				
				
			}

			@Override
			public void onStopTrackingTouch(SeekBar arg0) {
				
				
			}
			
		});
		
		/** END Interest Rate Seek Bar Listener
		/*******************************************************************************/
		
		
	}
	
	public void addDownPaymentListeners(){
		
		
		SeekBar homePriceSB = (SeekBar) findViewById(R.id.homePriceSlider);
		SeekBar downPaymentSB = (SeekBar) findViewById(R.id.downPaymentSlider);
		SeekBar interestRateSB = (SeekBar) findViewById(R.id.interestRateSlider);
		
		homePriceSB.setMax(800000);
		
		
		interestRateSB.setMax(10000);
		interestRateSB.incrementProgressBy(25);

		/**********************************************/
		/** home price on slider change listener  *****/
		/**********************************************/
		homePriceSB.setOnSeekBarChangeListener(new OnSeekBarChangeListener(){

			@Override
			public void onProgressChanged(SeekBar sb, int progress, boolean fromUser) {
				
				/** update home price value **/
				homePrice = progress/10000;
				homePrice = homePrice*10000;

				/** update the associated text values **/
				TextView homePriceSliderValue = (TextView) findViewById(R.id.homePriceText);
				TextView homePriceValue = (TextView) findViewById(R.id.HomePriceValue);
				
			    NumberFormat formatter = new DecimalFormat("$###,###");
			    //System.out.println("The Decimal Value is: "+formatter.format(homePrice));
				
			    
			    /** TODO BUG AT THIS SET TEXT **/
				homePriceValue.setText(formatter.format(homePrice));
				homePriceSliderValue.setText(formatter.format(homePrice));
				
				
				/**update db with new homePrice **/
				MortgageCalcActivity.this.dbhelper.updateHomePrice(homePrice);
				
				/*************************************************************************** 
				 * update Down Payment Percentage
				 */
				
				TextView downPaymentValue = (TextView) findViewById(R.id.downPaymentText);
				int downPaymentInt = Integer.parseInt(downPaymentValue.getText().toString().replace("$","").replace(",", ""));
				
				/** double values of integers **/
				double dDownPayment = (double) downPaymentInt;
				double dHomePrice = (double) homePrice;
				double downPaymentPercent = -1;
				
				/** text view containing DP percent **/
				TextView downPaymentPercentText = (TextView) findViewById(R.id.downPaymentPercentageText);
				
				if(dHomePrice != 0){
					downPaymentPercent = dDownPayment/dHomePrice*100;
				}
				
				/** if a proper percentage, display it **/
				if(downPaymentPercent >= 0 && dHomePrice > dDownPayment){

					//Log.e("down Payment Int", "downPayment int = " + downPaymentPercent);
					NumberFormat percentFormatter = new DecimalFormat("(#.00%)");
					
					downPaymentPercentText.setText(percentFormatter.format(downPaymentPercent/100)); // I dont know why, but I had to divide the percent by 100 again
					
					downPaymentPercentText.setVisibility(View.VISIBLE);
					
				}
				/** else do not display the percentage **/
				else{
					downPaymentPercentText.setVisibility(View.GONE);
				}
				
				/** End updating down payment percent
				/***************************************************************************/
	
			}

			@Override
			public void onStartTrackingTouch(SeekBar arg0) {
				
			}

			@Override
			public void onStopTrackingTouch(SeekBar arg0) {
				
				updatePieChart();
				
				updateCalculations();
				
			}
			
		});
		
		
		/**********************************************/
		/** Down Payment Slider Change Listener*  *****/
		/**********************************************/
		downPaymentSB.setOnSeekBarChangeListener(new OnSeekBarChangeListener(){

			@Override
			public void onProgressChanged(SeekBar sb, int progress, boolean fromUser) {
				
				/** scale down payment to increments of 500**/
				downPayment = progress/500;
				downPayment = downPayment*500;
				
				/** update the associated text values **/
				TextView downPaymentSliderValue = (TextView) findViewById(R.id.downPaymentText);
				
				NumberFormat formatter = new DecimalFormat("$###,###");
				
				downPaymentSliderValue.setText(formatter.format(downPayment));
				
				
				
				/** update the down payment text in the pie Chart **/
				TextView pieChartDPText = (TextView) findViewById(R.id.pieChartDownPaymentValue);
				if(pieChartDPText != null){
					//pieChartDPText.setText(formatter.format(downPayment));
				}
				
				/** update down payment in the DB **/
				MortgageCalcActivity.this.dbhelper.updateDownPaymentGoal(downPayment);
				
				/**********************************************************************/
				/** update the Down Payment Percent 								 **/
				
				TextView homePriceValue = (TextView) findViewById(R.id.homePriceText);
				/** get integer value and strip $ and ,'s **/
				int homePriceInt = Integer.parseInt(homePriceValue.getText().toString().replace("$", "").replace(",", ""));
				
				/** double values of integers **/
				double dDownPayment = (double) downPayment;
				double dHomePrice = (double) homePriceInt;
				double downPaymentPercent = -1;
				
				/** text view containing DP percent **/
				TextView downPaymentPercentText = (TextView) findViewById(R.id.downPaymentPercentageText);
				
				if(dHomePrice != 0){
					//Log.e("TEST", dDownPayment + " " + dHomePrice + " " + dDownPayment/dHomePrice);
					downPaymentPercent = dDownPayment/dHomePrice*100;
				}
				
				/** if a proper percentage, display it **/
				if(downPaymentPercent >= 0 && dHomePrice > dDownPayment){

					//Log.e("down Payment Int", "downPayment int = " + downPaymentPercent);
					NumberFormat percentFormatter = new DecimalFormat("(#.00%)");
					
					downPaymentPercentText.setText(percentFormatter.format(downPaymentPercent/100)); // I dont know why, but I had to divide the percent by 100 again
					
					downPaymentPercentText.setVisibility(View.VISIBLE);
					
				}
				/** else do not display the percentage **/
				else{
					downPaymentPercentText.setVisibility(View.GONE);
				}
				
				
				
				
				
				/** END update Down Payment Percent      							 **/
				/**********************************************************************/
				
				//redrawPieChart();
				
		
			}

			@Override
			public void onStartTrackingTouch(SeekBar arg0) {
				
			}

			@Override
			public void onStopTrackingTouch(SeekBar seekBar) {
				/** scale down payment to increments of 500**/
				int progress = seekBar.getProgress();
				downPayment = progress/500;
				downPayment = downPayment*500;
				
				/** update the associated text values **/
				TextView downPaymentPieChartText = (TextView) findViewById(R.id.pieChartDownPaymentValue);
				
				NumberFormat formatter = new DecimalFormat("$###,###");
				
				downPaymentPieChartText.setText(formatter.format(downPayment));
				
				updateCalculations();
				
				updatePieChart();
			}
			
		});
		
		/**********************************************/
		/** Interest Rate On Slider Change Listener ***/
		/**********************************************/
		interestRateSB.setOnSeekBarChangeListener(new OnSeekBarChangeListener(){
			@Override
			public void onProgressChanged(SeekBar sb, int progress, boolean fromUser) {
				
				
				/**
				 * formats the interest rate to be between 0-10% with %.25 intervals
				 */
				int tempRate = progress;
				tempRate = tempRate/250;
				tempRate = tempRate*250;
				
				MortgageCalcActivity.this.interestRate = (double)tempRate;
				MortgageCalcActivity.this.interestRate = interestRate/1000;
				
				/** update the associated text values **/
				TextView interestRateSliderValue = (TextView) findViewById(R.id.interestRateText);

				/** Convert to Decimal format with 2 decimal Places **/
				DecimalFormat df = new DecimalFormat("0.00");
				
				
				
				interestRateSliderValue.setText(df.format(interestRate).toString()+"%");
				
				/** save interest rate to DB **/
				//MortgageCalcActivity.this.calcDBHelper.updateInterestRate(interestRate);
		
			}

			@Override
			public void onStartTrackingTouch(SeekBar arg0) {
				
				
			}

			@Override
			public void onStopTrackingTouch(SeekBar arg0) {
				
				
				/** save interest rate to DB **/
				MortgageCalcActivity.this.calcDBHelper.updateInterestRate(interestRate);
				
				MortgageCalcActivity.this.updateCalculations();
				
			}
			
		});
	}
	
	
	/**
	 * add the slider and button listeners to the activity
	 */
	protected void addListeners(){
		
		/****************************************************************************************/
		/** Initialize Down Payment Calc switch button 					*************************/
		Button downPaymentCalcButton = (Button) findViewById(R.id.downPaymentCalcButton);
		
		
		downPaymentCalcButton.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View arg0) {
			
				
				if(downPaymentCalcSelected == true){
					/** do nothing, already on this view **/
					Log.e("MC", "Already Down Payment Selected");
				}
				else{
					
					/** change toggle button images and text **/
					Button downPaymentCalcButton = (Button) findViewById(R.id.downPaymentCalcButton);
					downPaymentCalcButton.setBackgroundResource(R.drawable.mort_calc_right_selected);
					downPaymentCalcButton.setTextColor(Color.WHITE);
					
					
					Button affordabilityCalcButton = (Button) findViewById(R.id.affordabilityCalcButton);
					affordabilityCalcButton.setBackgroundResource(R.drawable.mort_calc_left_unselected);
					affordabilityCalcButton.setTextColor(Color.BLACK);
					
					/** change to down payment calc view **/
					LayoutInflater layoutInflater = (LayoutInflater) 
					        MortgageCalcActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
					
					LinearLayout mortCalcMainContentLayout = (LinearLayout) findViewById(R.id.mortCalcContentLayout);
					
					
					/** inflate down payment calc layout **/
					mortCalcMainContentLayout.removeAllViews();
					mortCalcMainContentLayout.addView(layoutInflater.inflate(R.layout.downpayment_calc_layout, mortCalcMainContentLayout, false));
					
					

					//Log.e("Mort Calc", "CLICKED DOWN PAYMENT BUTTON");
					
					downPaymentCalcSelected = true;
					
					
					
					addPieChart();
					
					restoreDownPaymentCalcDBValues();
					
					MortgageCalcActivity.this.updateCalculations();
					
					addListeners();
					
				}
			}
		});
		
		
		/****************************************************************************************/
		/** Initialize Affordability Calc switch button 				*************************/
		
		Button affordabilityCalcButton = (Button) findViewById(R.id.affordabilityCalcButton);
		
		affordabilityCalcButton.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View arg0) {
				
				if(downPaymentCalcSelected == true){
					
					/** change toggle button images and text **/
					Button downPaymentCalcButton = (Button) findViewById(R.id.downPaymentCalcButton);
					downPaymentCalcButton.setBackgroundResource(R.drawable.mort_calc_right_unselected);
					downPaymentCalcButton.setTextColor(Color.BLACK);
					
					
					Button affordabilityCalcButton = (Button) findViewById(R.id.affordabilityCalcButton);
					affordabilityCalcButton.setBackgroundResource(R.drawable.mort_calc_left_selected);
					affordabilityCalcButton.setTextColor(Color.WHITE);
					
					/** change affordability calc view **/
					LayoutInflater layoutInflater = (LayoutInflater) 
					        MortgageCalcActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
					
					LinearLayout mortCalcMainContentLayout = (LinearLayout) findViewById(R.id.mortCalcContentLayout);
					
					mortCalcMainContentLayout.removeAllViews();
					mortCalcMainContentLayout.addView(layoutInflater.inflate(R.layout.affordability_calc_layout, mortCalcMainContentLayout, false));
					
					downPaymentCalcSelected=false;
					
					addAffordabilityListeners();
					
					
					//Log.e("MORT CALC", "CLICKED AFFORD CALC BUTTON");
					
					restoreAffordabilityCalcDBValues();
					
					updateAffordabilityCalculations();
					
				}
				else{
					/** do nothing, already on this view **/
					Log.e("MC", "Already Affordable selected");
				}
			}
		});
		
		
		if(downPaymentCalcSelected){
			addDownPaymentListeners();
			restoreDownPaymentCalcDBValues();
		}
		else{
			addAffordabilityListeners();
			restoreAffordabilityCalcDBValues();
		}
		
		

	}


	/**
	 * Scale the progress bar to represent $values for prices (ie: 100 --> $1,000,000)
	 * @param progress the position of the seekBar
	 * @return a scaled value of the progress bar
	 */
	protected int scale(int progress) {
		/** TODO scale algorithm **/
		return progress;
	}
	
	
	/**
	 * given info, calculates the MONTHLY mortgage insurance cost, and updates the value
	 * @return
	 */
	public double calculateMortgageInsurance(){
		/** TODO: this **/
		double loanAmount = this.homePrice-this.downPayment;
		
		/** loan to value. the percent of the loan to the house price **/
		double ltv = loanAmount/this.homePrice;
		//Log.e("ltv", "ltv == " + ltv);
		
		/** 
		 * calculate the PMI Rate. depends on down payment
		 * formula's taken from 
		 * http://www.dailyinterest.com/library/PMI/How_to_calculate_PMI.html
		 * 
		 **/
		
		double pmiRate = -1;
		
		if(ltv >= .9501){
			pmiRate=.0090;
		}
		
		else if(ltv >= .9001 && ltv <= .95){
			pmiRate = .0078;
		}
		else if(ltv >=.8501 && ltv <= .90){
			pmiRate = .0052;
		}
		else if(ltv >= .8001 && ltv <= .85){
			pmiRate = .0032;
		}
		else if (ltv <= .80) pmiRate = 0;
		
		double yearlyPMI = loanAmount*pmiRate;
		
		double monthlyPMI = yearlyPMI/12;
		
		return monthlyPMI;
		
	}
	
	/**
	 * given info, calculates the home owner insurance cost and updates value
	 * @return
	 */
	public double calculateHomeOwnersInsurance(){
		/** TODO this **/
		
		/**
		 * formula seen here http://homeguides.sfgate.com/average-cost-homeowners-insurance-3020.html
		 */
		
		double homeInsurance = this.homePrice/1000;
		homeInsurance *= 3.5;
		
		/** divide by 12 for monthly amount **/
		homeInsurance = homeInsurance/12;
		
		return homeInsurance;
	}
	
	/**
	 * given info, calculates the property tax for the house cost and updates value
	 * @return
	 */
	public double calculatePropertyTax(){
		/** TODO this **/
		double propertyTaxAverage = .0015; /** average = 1.5% **/
		
		double propertyTax = this.homePrice*propertyTaxAverage;
		
		return propertyTax;
	}
	
	
	public double calculateAffordableHome(){
		
		//get the Monthly Income
		double monthlyIncome = this.monthlyIncome;//60000/12;
		
		//get the monthly Debts
		int monthlyDebts = this.monthlyExpenses;
		
		Log.e("expenses", "monthlyExpenses = " + this.monthlyExpenses);
		
		//get the APR
		double five = 5;
		double hundred = 100;
		double APR = this.interestRate/100;//five/hundred;
		Log.e("afford", "APR = " + APR);
		
		//the period interest rate
		double periodInterestRate = APR/12;
		Log.e("afford", "period Interest Rate = " + periodInterestRate);
		
		//payments per lifetime of loan
		//360 for 30 year mortgage
		int ppl = 360;
		

		
		/**
		 * the amount you can dedicate to paying all debts
		 * assumes a rate of .36%
		 */
		double spendableRate = .36;
		double totalSpendable = monthlyIncome*spendableRate;
		
		/**
		 * the amount of money you can dedicate to paying mortgage
		 * assumes user can spend .30 of income on paying house
		 */
		double homeSpendableRate = .33;
		double homeSpendable = monthlyIncome*homeSpendableRate;
		
		if(totalSpendable - this.monthlyExpenses < homeSpendable){
			homeSpendable = totalSpendable - this.monthlyExpenses;
		}
		
		Log.e("afford", "homespendable = " + homeSpendable);
		
		//TODO check math for homeSpendable
		
		
		double annualProperyTax = 3500;
		double annualHomeInsurance = 481;
		
		/**
		 * the monthly principal and interest amount == homespendable - the monthly costs of property tax and home insurance
		 */
		double principalAndInterest = homeSpendable - (annualProperyTax + annualHomeInsurance)/12;
		Log.e("afford", "PaI = " + principalAndInterest);
		
		/**
		 * TODO
		 * get currrent interest rate from slider
		 */
		Log.e("afford", "periodInterestRate = " + periodInterestRate);
		
		
//		double A = periodInterestRate * Math.pow((1+periodInterestRate), ppl);
//		
//		double B = Math.pow(1+periodInterestRate, ppl) - 1;
		
		
		/**
		 * A = [ c * (1+c)^n]
		 */
		double A = periodInterestRate*Math.pow(1+periodInterestRate, ppl);
		
		/**
		 * B = [(1+c)^n-1]
		 */
		double B = Math.pow(1+periodInterestRate, ppl) - 1;
		
		//Log.e("A", " A = " + A );
		
		//Log.e("B", "B = " + B);
		
		double AdivB= (A/B);
		
		
		/**
		 * loanPrice = PrincipalAndInterest/(A/B);
		 */
		double loanPrice = principalAndInterest/AdivB;
		
		
		Log.e("AFFORDABILITY", "You can afford a house about $" + loanPrice);
		
		Log.e("afford", "monthly mortage payment = " + principalAndInterest +  (annualProperyTax + annualHomeInsurance)/12);
		
		
		TextView affordableAmount = (TextView) findViewById(R.id.qualifiedValue);
		
		if(loanPrice > 0){
			
			affordableAmount.setText(formatter.format(loanPrice));
			
			TextView tenPercentValue = (TextView) findViewById(R.id.tenPercentValue);
			tenPercentValue.setText(formatter.format(loanPrice*.10));
			
			TextView threePercentValue = (TextView) findViewById(R.id.threePercentValue);
			threePercentValue.setText(formatter.format(loanPrice*.035));
			
		}
		else{
			affordableAmount.setText("$0");
			
			TextView tenPercentValue = (TextView) findViewById(R.id.tenPercentValue);
			tenPercentValue.setText(formatter.format(0));
			
			TextView threePercentValue = (TextView) findViewById(R.id.threePercentValue);
			threePercentValue.setText(formatter.format(0));
		}
		
		
		//set the Downpayment percentages :
		

		
		
		return 0;
	}
	
	
	/**
	 * calculates the principle payment for the home
	 * @return
	 */
	public double calculatePrinciple(){
		
		
		/** determine the amount of payments per loan **/
		/** usually 30 yr, 12x a year = 360 payments **/
		int ppl = 360; /** 360 payments per loan **/
				
		/** period interest rate = APR / 12 months **/
		
		double periodInterestRate = this.interestRate/100;
		periodInterestRate = periodInterestRate/12;
		
		//Log.e("period interst ", "period interest = " +periodInterestRate);
		
		
		/** loan is what you haven't put for the down payment **/
		double loanPrice = this.homePrice - this.downPayment;
		
		//Log.e("loan price", "loan price = " + loanPrice);
		
		/** the total loan payment for this month **/
		/**
		 * P = L [ c * (1+c)^n ] / [(1+c)^n-1]
		 */
		
		/**
		 * A = [ c * (1+c)^n]
		 */
		double A = periodInterestRate*Math.pow(1+periodInterestRate, ppl);
		
		/**
		 * B = [(1+c)^n-1]
		 */
		double B = Math.pow(1+periodInterestRate, ppl) - 1;
		
		//Log.e("A", " A = " + A );
		
		//Log.e("B", "B = " + B);
		
		double payment = loanPrice*(A/B);
		
		//Log.e("Payment", "payment = " + payment);
		
		/** the interest payment for this month **/
		//double interestPayment = periodInterestRate*loanPrice;
		
		//Log.e("interest Pyament", "interest payment = " + interestPayment);
		
		/** the principle payment for this month **/
		double principlePayment = payment; // - interestPayment;
		
		this.principal = (int) principlePayment;
		
		return principlePayment;
		
	}
	
	public int exponentialScale(int currentProgress, int maxValue){
		
		double percentProgress = currentProgress/100;
		
		double v = (Math.exp(2.77258872 * percentProgress) - 1) / 15;
		
		v*=maxValue;
		
		if(percentProgress == 0) return 0;
		if(percentProgress == 1) return maxValue;
		if(v<0) return 0;
		if(v>maxValue) return maxValue;
		
		int result = (int) Math.ceil(v);
		
		return result;
		
		
		
		
	}
	
	public void addPieChart(){
		
		LayoutInflater layoutInflater = (LayoutInflater) 
		        MortgageCalcActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
		
		/** find the view containing the mortgage calculator **/
		LinearLayout mortCalcMainContentLayout = (LinearLayout) findViewById(R.id.mortCalcContentLayout);
		
		/**find the layout that will contain the pie chart **/
		LinearLayout pieChartLayout = (LinearLayout) findViewById(R.id.downPaymentPieChartLayout);
		
		/** add the down payment pie chart to the layout **/
		
		pieChartLayout.addView(layoutInflater.inflate(R.layout.down_payment_pie_chart_layout, mortCalcMainContentLayout, false));
		
		
		//mortCalcMainContentLayout.addView(layoutInflater.inflate(R.layout.downpayment_calc_layout, mortCalcMainContentLayout, false));
		
		LinearLayout chartLayout = (LinearLayout) mortCalcMainContentLayout.findViewById(R.id.chart);
		
		
		TextView downPaymentText = (TextView) findViewById(R.id.principleValue);
		TextView mortgageInsuranceText = (TextView) findViewById(R.id.MortgageInsuranceValue);
		TextView homeownersInsuranceText = (TextView) findViewById(R.id.HomeownersInsuranceValue);
		TextView propertyTaxText = (TextView) findViewById(R.id.propertyTaxValue);
		
		int downPayment = Integer.parseInt(downPaymentText.getText().toString().replace("$", "").replace(",", ""));
		int mortgage = Integer.parseInt(mortgageInsuranceText.getText().toString().replace("$", "").replace(",", ""));
		int homeowners = Integer.parseInt(homeownersInsuranceText.getText().toString().replace("$", "").replace(",", ""));
		int property = Integer.parseInt(propertyTaxText.getText().toString().replace("$", "").replace(",", ""));
		
		GraphicalView chartView = PieChartTest.getNewInstance(MortgageCalcActivity.this, downPayment, mortgage, homeowners, property);
		
		chartLayout.removeAllViewsInLayout();
		chartLayout.addView(chartView);
		
		
	}
	
	public void updatePieChart(){
		
		/** find the view containing the mortgage calculator **/
		LinearLayout mortCalcMainContentLayout = (LinearLayout) findViewById(R.id.mortCalcContentLayout);
		
		LinearLayout chartLayout = (LinearLayout) mortCalcMainContentLayout.findViewById(R.id.chart);
		
		TextView downPaymentText = (TextView) findViewById(R.id.principleValue);
		TextView mortgageInsuranceText = (TextView) findViewById(R.id.MortgageInsuranceValue);
		TextView homeownersInsuranceText = (TextView) findViewById(R.id.HomeownersInsuranceValue);
		TextView propertyTaxText = (TextView) findViewById(R.id.propertyTaxValue);
		
		int downPayment = 0;
		try{
			downPayment = Integer.parseInt(downPaymentText.getText().toString().replace("$", "").replace(",", ""));
		}
		catch(NumberFormatException e){
			
		}
		
		int mortgage = Integer.parseInt(mortgageInsuranceText.getText().toString().replace("$", "").replace(",", ""));
		int homeowners = Integer.parseInt(homeownersInsuranceText.getText().toString().replace("$", "").replace(",", ""));
		int property = Integer.parseInt(propertyTaxText.getText().toString().replace("$", "").replace(",", ""));
		
		GraphicalView chartView = PieChartTest.getNewInstance(MortgageCalcActivity.this, downPayment, mortgage, homeowners, property);
		chartLayout.removeAllViewsInLayout();
		
		chartLayout.addView(chartView);
	}
	
	public void redrawPieChart(){
		
		LinearLayout mortCalcMainContentLayout = (LinearLayout) findViewById(R.id.mortCalcContentLayout);
		LinearLayout chartLayout = (LinearLayout) mortCalcMainContentLayout.findViewById(R.id.chart);
		
		chartLayout.refreshDrawableState();

		
	}
	
	public void restoreDownPaymentCalcDBValues(){
		
		/** get the down payment total from the DB **/
		this.downPayment = (int) this.dbhelper.selectGoalTotal();
		
		/** get the home price **/
		this.homePrice = this.dbhelper.selectHomePrice();
		
		/** get interest rate **/
		this.interestRate = this.calcDBHelper.selectInterestRate();
		
		
		
		/** add them to the fields **/
		TextView downPaymentText = (TextView) findViewById(R.id.downPaymentText);
		downPaymentText.setText("" + formatter.format(downPayment));
		
		TextView downPaymentPieChartText = (TextView) findViewById(R.id.pieChartDownPaymentValue);
		downPaymentPieChartText.setText(formatter.format(downPayment));
		
		TextView homePriceText = (TextView) findViewById(R.id.homePriceText);
		homePriceText.setText("" + formatter.format(homePrice));
		
		TextView homePriceTableText = (TextView) findViewById(R.id.HomePriceValue);
		homePriceTableText.setText(formatter.format(homePrice));
		
		TextView interestRateText = (TextView) findViewById(R.id.interestRateText);
		interestRateText.setText(this.interestRate+"%");
		
		
		/** update slider progresses **/
		SeekBar downPaymentSlider = (SeekBar) findViewById(R.id.downPaymentSlider);
		downPaymentSlider.setProgress(downPayment);
		
		SeekBar homePriceSlider = (SeekBar) findViewById(R.id.homePriceSlider);
		homePriceSlider.setProgress(homePrice);
		
		SeekBar interestRateSlider = (SeekBar) findViewById(R.id.interestRateSlider);
		
		/** must scale the rate to fit the slider **/
		interestRateSlider.setProgress((int) (this.interestRate*1000));
		
		updateDPPercent();
		
		updatePieChart();
		
		
	}
	
	public void restoreAffordabilityCalcDBValues() {
		// TODO Auto-generated method stub
		
		/** restore the following fields **/
		TextView monthlyIncomeText = (TextView) findViewById(R.id.monthlyIncomeText);
		TextView monthlyExpensesText = (TextView) findViewById(R.id.monthlyExpensesText);
		TextView interestRateText = (TextView) findViewById(R.id.interestRateAffordabilityText);
		
		
		this.monthlyIncome = this.calcDBHelper.selectIncome();
		monthlyIncomeText.setText(formatter.format(this.monthlyIncome));
		
		this.monthlyExpenses = this.calcDBHelper.selectExpenses();
		monthlyExpensesText.setText(formatter.format(this.monthlyExpenses));
		
		this.interestRate = this.calcDBHelper.selectInterestRate();
		interestRateText.setText(this.interestRate+"%");
		
		
		/**update sliders as well **/
		SeekBar incomeSlider = (SeekBar) findViewById(R.id.monthlyIncomeSlider);
		SeekBar expensesSlider = (SeekBar) findViewById(R.id.monthlyExpensesSlider);
		SeekBar interestSlider = (SeekBar) findViewById(R.id.interestRateAffordabilitySlider);
		
		incomeSlider.setProgress(this.monthlyIncome);
		expensesSlider.setProgress(this.monthlyExpenses);
		interestSlider.setProgress((int) (this.interestRate*1000)); /** must scale Interest rate to match slider progress **/
		
	}
	
	public void updateDPPercent(){

	
				
		TextView homePriceValue = (TextView) findViewById(R.id.homePriceText);
		/** get integer value and strip $ and ,'s **/
		int homePriceInt = Integer.parseInt(homePriceValue.getText().toString().replace("$", "").replace(",", ""));
		
		/** double values of integers **/
		double dDownPayment = (double) downPayment;
		double dHomePrice = (double) homePriceInt;
		double downPaymentPercent = -1;
		
		/** text view containing DP percent **/
		TextView downPaymentPercentText = (TextView) findViewById(R.id.downPaymentPercentageText);
		
		if(dHomePrice != 0){
			//Log.e("TEST", dDownPayment + " " + dHomePrice + " " + dDownPayment/dHomePrice);
			downPaymentPercent = dDownPayment/dHomePrice*100;
		}
		
		
		/** if a proper percentage, display it **/
		if(downPaymentPercent >= 0 && dHomePrice > dDownPayment){
	
			//Log.e("down Payment Int", "downPayment int = " + downPaymentPercent);
			NumberFormat percentFormatter = new DecimalFormat("(#.00%)");
			
			downPaymentPercentText.setText(percentFormatter.format(downPaymentPercent/100)); // I dont know why, but I had to divide the percent by 100 again
			
			downPaymentPercentText.setVisibility(View.VISIBLE);
			
		}
		/** else do not display the percentage **/
		else{
			downPaymentPercentText.setVisibility(View.GONE);
		}

	}
	
	public void updateCalculations(){
		
		/** calculate the new principle payment **/
		double principle = calculatePrinciple();
		/** set the textview with the new value **/
		TextView principleText = (TextView) findViewById(R.id.principleValue);
		principleText.setText(formatter.format(principle));
		
		
		double mortgageInsurance = calculateMortgageInsurance();
		TextView mortgageInsuranceText = (TextView) findViewById(R.id.MortgageInsuranceValue);
		mortgageInsuranceText.setText(formatter.format(mortgageInsurance));
		
		
		double propertyTax = this.calculatePropertyTax();
		TextView propertyTaxText = (TextView) findViewById(R.id.propertyTaxValue);
		propertyTaxText.setText(formatter.format(propertyTax));
		
		double homeInsurance = this.calculateHomeOwnersInsurance();
		TextView homeInsuranceText = (TextView) findViewById(R.id.HomeownersInsuranceValue);
		homeInsuranceText.setText(formatter.format(homeInsurance));
		
		double monthlyMortgagePayment = principle + mortgageInsurance + propertyTax + homeInsurance;
		TextView monthlyMortgageText = (TextView)findViewById(R.id.monthlyMortgageValue);
		monthlyMortgageText.setText(formatter.format(monthlyMortgagePayment));
		
		TextView pieChartDP = (TextView) findViewById(R.id.pieChartDownPaymentValue);
		pieChartDP.setText(formatter.format(this.downPayment));
		
		updatePieChart();
		
	}
	
	public void updateAffordabilityCalculations(){
		
		
		TextView tenPercentText = (TextView) findViewById(R.id.tenPercentValue);
		tenPercentText.setText(formatter.format(this.homePrice*.10));
		
		TextView threePercentText = (TextView) findViewById(R.id.threePercentValue);
		threePercentText.setText(formatter.format(this.homePrice*.035));
		
		
	}

}
